/*
 * @Author: 郭桓
 * @Date: 2019-02-20 10:26:36
 * @LastEditors: GuoHuan
 * @LastEditTime: 2019-03-08 12:17:25
 * @Description: 工具类
 */
// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

class Utils {
    ///user/getPrize userId= 获取商品列表

    // /buyGoods/h5Order  totalFee= & userId = & account = & loginVar =
    //user/insertPrize? goodId= & loginVar = & telPhone= &address =&userName
    static singleton;
    constructor() {
        // this.baseUrl = 'http://192.168.31.108:80';

        // this.baseUrl = 'http://47.107.248.151:80';
        this.baseUrl = 'https://www.chaijunwenhua.com';
        this.shareUrl = 'https://www.chaijunwenhua.com';
        this.topY = 0;
        this.bottomY = 0;
        this.loadingNode = null;
        this.pay = 0;
        this._payGoodsId = -1;
        this._showInfo = [];
        this.toastNode = null;
        this.userinfo = {}; //用户信息
        this._toastY = 0;
        this.goodsList = []; //商品列表
        this.noticeList = [];

        cc.loader.loadRes("notice.json", function(err, text) {
            if (err == null) {
                this.noticeList = text.json;
            } else {
                this.noticeList = [{
                    name: '1378718****',
                    good: 'MAC Chili小辣椒',
                    state: '已从天猫发货'
                }, {
                    name: '1354745****',
                    good: 'YSL小金条21',
                    state: '已从天猫发货'
                }, {
                    name: '1882282****',
                    good: '阿玛尼小胖丁',
                    state: '正在备货'
                }, {
                    name: '1558205****',
                    good: '纪梵希小羊皮',
                    state: '已从天猫发货'
                }, {
                    name: '1369912****',
                    good: '兰蔻505',
                    state: '正在备货'
                }, {
                    name: '1330030****',
                    good: 'MAC Chili小辣椒',
                    state: '已从天猫发货'
                }, {
                    name: '1364749****',
                    good: 'MAC Chili小辣椒',
                    state: '正在备货'
                }, {
                    name: '1377723****',
                    good: 'YSL小金条21',
                    state: '正在备货'
                }, {
                    name: '1571751****',
                    good: 'MACRuby Woo',
                    state: '已从天猫发货'
                }, {
                    name: '1327208****',
                    good: 'MAC Chili小辣椒',
                    state: '已从天猫发货'
                }]
            }
            let uiJS = cc.director.getScene().getChildByName('Canvas').getComponent('MainActivity');
            if (uiJS) {
                uiJS.updateNotice(this.noticeList);
            }
        }.bind(this));

        // this.request('getWxShareConfig', 'GET', { jumpUrl: window.location.href, shareUrl: this.shareUrl }, function(err, data) {
        //     cc.log(err);
        //     if (err == null) {
        //         this.share(data);
        //     }
        // }.bind(this), false);
    }


    showShop() {
        this.loadingNode.active = true;
        this.loadingNode.getChildByName('shop').active = true;
        this.loadingNode.getChildByName('shop').getChildByName('gold').getComponent(cc.Label).string = this.userinfo.gold;


        // openId=oEFO40XULe8zvEaB6T_1XYCJt1IA
    }

    getGoodsList(cb) {
        if (this.goodsList != null && this.goodsList.length > 0) {
            if (cb) {
                cb(this.goodsList)
            }
        } else {
            this.request("goods/getList", "GET", {}, function(err, data) {
                if (err == null) {
                    this.goodsList = data.result;
                    if (cb) {
                        cb(this.goodsList);
                    }
                }

            }.bind(this), false);
        }
    }

    setLoadingNode(node) {
        this.loadingNode = node;
        cc.game.addPersistRootNode(this.loadingNode);
        this.loadingNode.active = false;
        this.topY = this.loadingNode.getChildByName('loading1').y;
        this.bottomY = this.loadingNode.getChildByName('loading2').y;
        this.toastNode = this.loadingNode.getChildByName('toast');
        this._toastY = this.toastNode.y;
    }

    startGame() {

    }

    setID(id) {
        this._payGoodsId = id;
    }

    getID() {
        return this._payGoodsId;
    }

    setPay(pay) {
        this.pay = pay;
    }

    getPay() {
        return this.pay;
    }

    //使用动画
    loadAnim(listen, shadow) {
        if (listen != null) {
            this.loadingNode.getChildByName('img_mission').getChildByName('mission').getComponent(cc.Label).string = listen;
        }

        if (shadow != null) {
            this.loadingNode.getChildByName('shadow').active = true;
            this.loadingNode.getChildByName('shadow').opacity = shadow;
        }

        this.loadingNode.active = true;
        let imgTop = this.loadingNode.getChildByName('loading1');
        let imgBottom = this.loadingNode.getChildByName('loading2');
        let mission = this.loadingNode.getChildByName('img_mission');
        imgTop.y = this.topY + imgTop.height;
        imgBottom.y = this.bottomY - imgBottom.height;

        let anTime = 0.2;
        imgTop.runAction(cc.moveTo(anTime, cc.v2(imgTop.x, this.topY)));
        imgBottom.runAction(cc.moveTo(anTime, cc.v2(imgBottom.x, this.bottomY)));

        mission.scale = 0;
        mission.runAction(cc.sequence(cc.delayTime(anTime + 0.1), cc.scaleTo(0.2, 1.1)));
    }

    loading(string) {
        this.loadingNode.active = true;
        this.toastNode.active = false;
        this.loadingNode.getChildByName('shadow').active = true;
        this.loadingNode.getChildByName('loading1').active = false;
        this.loadingNode.getChildByName('loading2').active = false;
        this.loadingNode.getChildByName('img_mission').active = false;

        this.loadingNode.getChildByName('img_loading').active = true;
        this.loadingNode.getChildByName('loadingmsg').active = true;
        this.loadingNode.getChildByName('img_loading').runAction(cc.repeatForever(cc.rotateBy(1, -360)));

        if (string == null) {
            string = '';
        }
        this.loadingNode.getChildByName('loadingmsg').getComponent(cc.Label).string = string;
    }

    dismissLoading() {
        this.loadingNode.getChildByName('img_loading').stopAllActions();
        this.loadingNode.getChildByName('img_loading').active = false;
        this.loadingNode.getChildByName('loadingmsg').active = false;
        this.loadingNode.getChildByName('shadow').active = false;
        if (this.loadingNode.active && this.loadingNode.getChildByName('shop').active) {
            return;
        }

        this.loadingNode.active = false;
    }

    getUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                arr = arrPara[i].split("=");

                if (arr != null && arr[0] == paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }

    /**
     * @description: 游戏开始后的关卡动画 去除
     * @param {type} 
     * @return: 
     */
    gameStartAnim(isCheck) {
        if (!this.loadingNode.active) {
            return;
        }
        if (isCheck) {
            if (Math.abs(this.loadingNode.getChildByName('loading2').y - this.bottomY) > 10) {
                setTimeout(() => {
                    this.gameStartAnim(true);
                }, 1000);
                return;
            }
        }
        this.loadingNode.getChildByName('img_loading').active = false;
        this.loadingNode.getChildByName('loadingmsg').active = false;
        let imgTop = this.loadingNode.getChildByName('loading1');
        let imgBottom = this.loadingNode.getChildByName('loading2');
        let mission = this.loadingNode.getChildByName('img_mission');
        imgTop.active = true;
        imgBottom.active = true;
        mission.active = true;
        mission.scale = 0;
        let anTime = 0.2;
        imgTop.runAction(cc.moveTo(anTime, cc.v2(imgTop.x, this.topY + imgTop.height)));
        imgBottom.runAction(cc.moveTo(anTime, cc.v2(imgBottom.x, this.bottomY - imgBottom.height)));


        this.loadingNode.runAction(cc.sequence(cc.delayTime(anTime + 0.1), cc.callFunc(function() {
            this.loadingNode.active = false;
        }.bind(this), this)));
    }


    randomNums(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    }



    gotoGame(gooditem) {
        this.setID(gooditem.id);
        this.pay = gooditem.need;
        this.loadingNode.active = true;
        this.loadingNode.getChildByName('img_loading').active = false;
        this.loadingNode.getChildByName('loadingmsg').active = false;
        this.loadingNode.getChildByName('shadow').active = true;
        this.loadingNode.getChildByName('shadow').opacity = 0;

        this.loadingNode.getChildByName('loading1').active = true;
        this.loadingNode.getChildByName('loading2').active = true;
        this.loadingNode.getChildByName('img_mission').active = true;
        this.loadingNode.getChildByName('loading1').y = this.topY;
        this.loadingNode.getChildByName('loading2').y = this.bottomY;
        this.loadingNode.getChildByName('img_mission').scale = 1;
        this.loadingNode.getChildByName('img_mission').getChildByName('mission').getComponent(cc.Label).string = 1;


        cc.director.loadScene('game', function() {
            this.gameStartAnim();
        }.bind(this));
    }




    /**
     * @description: 体验游戏
     * @param {type} 
     * @return: 
     */
    testGame() {
        this.setID(-1);
        this.pay = 0;
        this.loadingNode.active = true;
        this.loadingNode.getChildByName('img_loading').active = false;
        this.loadingNode.getChildByName('loadingmsg').active = false;
        this.loadingNode.getChildByName('shadow').active = true;
        this.loadingNode.getChildByName('shadow').opacity = 0;

        this.loadingNode.getChildByName('loading1').active = true;
        this.loadingNode.getChildByName('loading2').active = true;
        this.loadingNode.getChildByName('img_mission').active = true;
        this.loadingNode.getChildByName('loading1').y = this.topY;
        this.loadingNode.getChildByName('loading2').y = this.bottomY;
        this.loadingNode.getChildByName('img_mission').scale = 1;
        this.loadingNode.getChildByName('img_mission').getChildByName('mission').getComponent(cc.Label).string = 1;


      
        this.request("canStart", "GET", {
            needGold: 0,
            goodId:-1,
            loginVar: this.userinfo.loginId
        }, function(err, data) {
            if (err == null) {
             
            }
        }.bind(this),false);

        cc.director.loadScene('game', function() {
            this.gameStartAnim();
        }.bind(this));

    }

    animOver() {
        this.toastNode.active = false;
        this.animStart();
    }

    animStart() {
        if (this.toastNode.active)
            return;
        if (this._showInfo == null || this._showInfo.length == 0) {
            if (this.loadingNode.active && this.loadingNode.getChildByName('shop').active) {
                return;
            }
            this.loadingNode.active = false;
            this.loadingNode.getChildByName('shadow').active = false;
            return;
        }
        var msgInfo = this._showInfo.shift();
        if (msgInfo.msg == null || msgInfo.msg.length == 0) {
            this.animStart();
            return;
        }
        if (!this.loadingNode.active) {
            this.loadingNode.active = true;
            this.loadingNode.getChildByName('shadow').active = false;
        }
        this.toastNode.stopAllActions();
        this.toastNode.active = true;
        this.toastNode.getChildByName('words').getComponent(cc.Label).string = msgInfo.msg;
        this.toastNode.y = this._toastY;
        this.toastNode.opacity = 255;
        this.toastNode.runAction(cc.sequence(cc.delayTime(msgInfo.time), cc.callFunc(this.animOver.bind(this), this)));

        if (msgInfo.time > 1) {
            this.toastNode.runAction(cc.sequence(cc.moveBy(0.3, cc.v2(0, 50)), cc.delayTime(msgInfo.time - 1), cc.fadeTo(1, 0), cc.callFunc(this.animOver.bind(this), this)));
        } else {
            this.toastNode.runAction(cc.sequence(cc.delayTime(msgInfo.time), cc.callFunc(this.animOver.bind(this), this)));
        }
    }

    showToast(words, time) {
        if (time == null)
            time = 2;
        if (this._showInfo.length > 0) {
            if (words === this._showInfo[this._showInfo.length - 1].msg)
                return;
        }
        this._showInfo.push({
            msg: words,
            time: time
        });
        this.animStart();
    }
    /**
     * 游戏开始时的登陆
     */
    startLogin(callFunc) {
        var loginValue = cc.sys.localStorage.getItem("usrinfo"); //账号凭证 
        let from = this.getUrlParam('from');
        if (loginValue == null || loginValue.length == 0) {
            //需要重新获取
            this.request("user/getInfo", "GET", { from: from }, callFunc);
        } else {
            loginValue = JSON.parse(loginValue);
            this.request("user/getInfo", "GET", { from: from, loginVar: loginValue.loginId }, function(err, data) {
                if (err == null) {
                    data.loginId = loginValue.loginId;
                    callFunc(err, data);
                } else {
                    //玩家不存在的时候。直接重新登陆
                    this.request("user/getInfo", "GET", {}, callFunc);
                }
            }.bind(this));
        }
    }



    request(method, type, data, callFunc, isShowWindow, timeout) {
        try {
            var xhr = cc.loader.getXMLHttpRequest();
            var mHttpType = type;
            if ((typeof(type) == 'string') && (type.toUpperCase() == 'POST' || type.toUpperCase() == 'GET')) {

                if (type.toUpperCase() == 'POST') {
                    method = this.baseUrl + '/' + method;
                    var newData = '';
                    for (var key in data) {
                        newData += key + '=' + data[key] + "&"
                    }
                    if (newData.lastIndexOf('&') > 0) {
                        newData = newData.substring(0, newData.length - 1);
                    }
                    data = newData;
                } else {
                    method = this.baseUrl + '/' + method + '?';
                    let isHasParam = false;
                    for (var key in data) {
                        method += key + '=' + data[key] + "&"
                        isHasParam = true;
                    }
                    if (method.lastIndexOf('&') > 0) {
                        method = method.substring(0, method.lastIndexOf('&'));
                    }

                    if (!isHasParam) {
                        method = method.substring(0, method.lastIndexOf('?'));
                    }

                }
                if (isShowWindow == null) {
                    isShowWindow = true;
                }
            } else {
                mHttpType = 'POST';
                isShowWindow = callback;
                callback = data;
                data = type;
                method = this.baseUrl + '/' + method;
                if (isShowWindow == null) {
                    isShowWindow = true;
                }
            }

            cc.log(this.baseUrl + '/' + method);
            if (isShowWindow) {
                if (typeof(isShowWindow) == 'string') {
                    this.loading(isShowWindow);
                } else {
                    this.loading('请稍等,数据正在获取中...');
                }
            }

            xhr.open(mHttpType, method, true);
            xhr.setRequestHeader("cache-control", "no-cache");
            xhr.setRequestHeader("contentType", "text/html;charset=uft-8") //指定发送的编码   
            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");


            if (timeout != null && typeof(timeout) == 'number') {
                xhr.timeout = timeout;
            }

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                    var httpStatus = xhr.statusText;
                    var response = xhr.responseText;
                    var resData;
                    var err = null;
                    if (isShowWindow) {
                        this.dismissLoading();
                    }
                    try {
                        cc.log(response);
                        resData = JSON.parse(response);
                        if (!resData.success) {
                            err = resData.msg;
                        }
                    } catch (ex) {
                        err = ex;
                    }
                    if (err != null) {
                        this.showToast(err);
                    }
                    if (callFunc)
                        callFunc(err, resData);
                }
            }.bind(this);
            if (data.timeout != null) {
                xhr.timeout = data.timeout;
                delete data.timeout;
            } else {
                xhr.timeout = 5000;
            }
            xhr.onerror = function() {
                if (isShowWindow) {
                    this.dismissLoading();
                }
                if (callFunc)
                    callFunc('网络连接失败', null);
            }.bind(this);
            xhr.ontimeout = function() {
                if (isShowWindow) {
                    this.dismissLoading();
                }
                if (callFunc)
                    callFunc('网络连接超时', null);
            }.bind(this);
            if (mHttpType == 'GET') {
                xhr.send();
            } else {
                xhr.send(data);
            }
        } catch (ex) {
            cc.log(ex);
        }
    }


    // share(json) {
    //     //    var str = "jsapi_ticket=" + wxdata.jsapi_ticket + "&noncestr=" + wxdata.nonce_str + "&timestamp=" + wxdata.timestamp + "&url=" + window.location.href.split('#')[0];

    //     json.debug = true;
    //     // debug: false, // 
    //     wx.config(json);

    //     wx.ready(function() {
    //         wx.onMenuShareTimeline({ //分享到朋友圈
    //             title: '闯三关,大牌口红任你挑！',
    //             link: this.shareUrl,
    //             desc: '耐住心,稳住手,大牌口红就到手.',
    //             imgUrl: 'https://www.chaijunwenhua.com/icon.png',
    //             type: 'link', // 分享类型,music、video或link，不填默认为link
    //             dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
    //             success: function() {

    //             },
    //             cancel: function() {

    //             }
    //         });

    //         wx.onMenuShareAppMessage({
    //             title: '闯三关大牌口红任你挑！',
    //             link: this.shareUrl,
    //             desc: '耐住心,稳住手,大牌口红就到手.',
    //             imgUrl: 'https://www.chaijunwenhua.com/icon.png',
    //             type: 'link', // 分享类型,music、video或link，不填默认为link
    //             dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
    //             success: function() {

    //             },
    //             cancel: function() {

    //             }
    //         });

    //     });

    //     wx.error(function(res) {
    //         console.log(res)
    //     });


    // }
}

export { Utils }